import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';
import { ApiService } from '../../../../core/services/http/api.service';
import { GridConfigService } from 'app/core/config/grid-config.service';
import { ActivatedRoute } from '@angular/router';
import { Events } from '../../../../core/services/events/Events';
import { ApesMessageService } from '../../../../shared/apes/message/index';
import { deepClone } from '../../../../utils/utils';
import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { ApesDrawerCustomGridComponent } from '@shared/ag-grid-ext/drawer-custom/drawer-custom-grid.component';
import { ApesDrawerService } from '@shared/apes/drawer';
import { DataKanbanDrawerComponent } from '../drawer/data-kanban-drawer.component';

@Component({
  selector: 'data-kanban-particulars',
  templateUrl: './data-kanban-particulars.component.html',
  styleUrls: ['./data-kanban-particulars.component.scss'],
})
export class DataKanbanParticularsComponent implements OnInit, OnDestroy {

  /* 按钮相关 */
  buttonBar = [
    { pageId: 'findByUnassigned', style: 'primary', label: '指派', id: 'action_new', loading: false },
    { pageId: 'findByUnassigned_show', style: 'default', label: '已派车运单', id: 'action_assigned', loading: false },
    { pageId: 'findByAssigned', style: 'primary', label: '重新指派', id: 'action_reset', loading: false },
  ];
  btnBar: any[] = [];
  pageId: any = '';
  tableText: any = '无数据';

  ctx = { model: {} };

  currentChauffeur: any; // 当前司机
  carInformationId: any; // 已指派车单

  /** Grid 相关 **/
  parmes: any;
  rowData: any[] = [];

  /** formly 配置 **/
  form = new FormGroup({});
  formId = 'tms/dataKanban/dataKanbanParticularsComponent';
  model: any = {};
  options: FormlyFormOptions = {};
  field: FormlyFieldConfig[] = [];
  fieldData: any[] = [
    {
      key: 'branchLineId',
      type: 'span',
      templateOptions: {
        label: '线路名称',
        valueFormatter: 'value.name',
      },
    },
    {
      key: 'carInformationId',
      type: 'span',
      templateOptions: {
        label: '派车单',
      },
      hide: false,
    },
    {
      key: 'chauffeur',
      type: 'select',
      templateOptions: {
        searchFormId: 'tms.chauffeur.findAll',
        downFormatter: '\'[ \' + value.id + \' ]\' + \' \' + value.name',
        valueFormatter: '\'[ \' + value.id + \' ]\' + \' \' + value.name',
        label: '指派司机',
        api: 'tms.chauffeur.findAllByKanBan',
        domain: '{"filters":[{"field":"name","operator":"like","value":"{{value}}"}],"groups":[],"operator":"and"}',
        disabled: false,
      },
    },
    {
      key: 'vehicle',
      type: 'select',
      templateOptions: {
        searchFormId: 'tms.vehicle.findAll',
        downFormatter: 'value.vehicleNumber + \' \' +  \'[ \' + value.vehicleStatus.description + \' ]\'',
        valueFormatter: 'value.vehicleNumber + \' \' +  \'[ \' + value.vehicleStatus.description + \' ]\'',
        label: '指派车辆',
        api: 'tms.vehicle.findAllByKanBan',
        domain: '{"filters":[{"field":"vehicleNumber","operator":"like","value":"{{value}}"}],"groups":[],"operator":"and"}',
        disabled: false,
      },
    },
  ];

  selectAll: boolean = false;


  constructor(
    private apiService: ApiService,
    private event: Events,
    private routeInfo: ActivatedRoute,
    private gridConfigService: GridConfigService,
    private cd: ChangeDetectorRef,
    private msg: ApesMessageService,
    protected expressionService: ExpressionService,
    protected drawerService: ApesDrawerService,
  ) {

  }

  ngOnInit() {
    this.event.subscribe(this.formId, () => {
      this.initData();
    });

    this.initData();

  }


  initData() {
    let value = this.gridConfigService.getRouterData();
    if (value.hasOwnProperty('formId') && value['formId'] == this.formId) {
      this.model = {};
      this.form = new FormGroup({});
      this.pageId = '';
      this.btnBar = [];
      this.field = [];
      this.parmes = value.data;

      this.pageId = this.parmes['id'];

      this.setBtnStatus();


      let api = this.parmes['api'];
      if (this.pageId == 'findByUnassigned') {
        this.initField('findByUnassigned');
      } else if (this.pageId == 'findByAssigned') {
        this.initField('findByAssigned');
      }

      let data = { ...this.model };

      this.searchListData(api, data);
    }
  }

  initField(id) {
    let localField = [];
    let _fieldData = deepClone(this.fieldData);
    _fieldData.forEach((field) => {
      if (id == 'findByAssigned') {
        field.templateOptions['disabled'] = true;
        field.templateOptions['divCol'] = '6';
        if (field.key == 'carInformationId') {
          field['hide'] = false;
        }
      } else if (id == 'findByUnassigned') {
        field.templateOptions['disabled'] = false;
        field.templateOptions['divCol'] = '8';
        if (field.key == 'carInformationId') {
          field['hide'] = true;
        }
      }

      // field.expressionProperties = { 'templateOptions.disabled': 'formState.disabled' };
      // let disabled = field.templateOptions['disabled'] || false;
      // field.templateOptions['disabled'] = this.expressionService.eval(disabled, {
      //   node: this.pageId,
      //   model: this.model,
      // });

      localField.push(field);

    });
    this.field = deepClone(localField);

    let result = {};
    for (let key in this.parmes) {
      let value = this.parmes[key];
      if (key === 'carInformation') {
        result['branchLineId'] = {};
        result['branchLineId']['name'] = value['branchLineId'];
        result['chauffeur'] = value['chauffeurId'];
        result['vehicle'] = value['vehicleId'];
        result['carInformationId'] = value['id'];
        result[key] = value;
      } else {
        result[key] = value;
      }
    }

    this.model = result;
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data: any) {

    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_new') {
        // this.buttonBar[0].loading = true;
        this.clickDesignate();
      } else if (data.id === 'action_reset') {
        this.resetDesignate();
      } else if (data.id === 'action_assigned') {
        this.assignedDesignate();
      }
    }
  }

  setBtnStatus() {
    this.buttonBar.forEach((btn) => {
      if (btn.pageId == this.pageId) {
        this.btnBar.push(btn);
      }
    });
  }

  // 确认指派
  clickDesignate() {

    let selectData = [];
    this.rowData.forEach((row) => {
      if (row.selected) {
        selectData.push(row);
      }
    });

    if (this.model['chauffeur'] == null) {
      this.msg.error('请选择指派司机');
      return;
    } else if (this.model['vehicle'] == null) {
      this.msg.error('请选择指派车辆');
      return;
    } else if (selectData.length == 0) {
      this.msg.error('请选择指派线路');
      return;
    }

    const data = {
      ...this.model,
      assignedList: selectData,
    };

    let api = 'tms.waybill.assignedByDetail';

    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {

      if (body) {
        this.msg.success('指派成功');
        let refreshApi = 'tms.waybill.unassignedDetail';
        this.searchListData(refreshApi, data);
      }
    });


  }

  // 重新指派
  resetDesignate() {
    let selectData = [];
    this.rowData.forEach((row) => {
      if (row.selected) {
        selectData.push(row);
      }
    });

    if (selectData.length == 0) {
      this.msg.error('请选择重新指派线路');
      return;
    }

    const data = {
      carInformation: this.model['carInformation'],
      waybill: selectData,
    };

    let api = 'tms.waybill.returnWaybill';

    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {

      if (body) {
        this.msg.success('重新指派成功');
        let refreshApi = 'tms.waybill.findByAssignedDetail';
        this.searchListData(refreshApi, data);
      }
    });
  }

  // 已指派车单
  assignedDesignate() {
    let drawer;
    let api = 'tms.waybill.findWaybillListByCarInformation';

    const openDrawer = drawer ? drawer : DataKanbanDrawerComponent;
    const drawerRef = this.drawerService.create<DataKanbanDrawerComponent, { api: string, data: any }, string>({
      apesTitle: '已派车运单',
      apesContent: openDrawer,
      apesWidth: '75vw',
      apesContentParams: {
        api: api,
        data: this.carInformationId,
      },
    });
    drawerRef.afterOpen.subscribe(() => {

    });
  }

  // 查询列表数据
  searchListData(api, data) {

    this.rowData = [];
    this.tableText = '查询中';

    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
      if (body) {
        this.rowData = body;
        if (this.rowData.length != 0) {
          this.rowData.forEach((row) => {
            row['selected'] = false;
          });
          this.selectAll = false;

          // this.cd.markForCheck();
          this.cd.detectChanges();

        } else {
          this.tableText = '无数据';
        }
      }
    });

  }

  // 点击全选
  clickSelectAll() {
    this.rowData.forEach((row) => {
      row['selected'] = this.selectAll;
    });
  }

  // 检查全选
  checkSelectAll() {
    let selectAll = true;
    this.rowData.forEach((row) => {
      if (row['selected'] == false) {
        return selectAll = false;
      }
    });
    this.selectAll = selectAll;
  }

  // 检查司机
  checkChauffeur() {

    if (this.model['chauffeur'] !== null) {
      let chauffeur = this.model['chauffeur']['name'];
      if (chauffeur && chauffeur != this.currentChauffeur) {

        this.currentChauffeur = chauffeur;

        let api = 'tms.waybill.findCarInformationByChauffeur';
        const data = {
          chauffeur: this.model['chauffeur'],
        };

        this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
          console.log(body);
          this.btnBar = [];
          if (body) {
            let id = body['carInformationId'];
            if(id != ''){
              this.carInformationId = id;

              this.buttonBar.forEach((btn) => {
                if (btn.pageId == 'findByUnassigned_show' || btn.pageId == this.pageId) {
                  this.btnBar.push(btn);
                }
              });
            }else {
              this.setBtnStatus();
            }
          }
        });
      }
    } else {
      this.currentChauffeur = '';
      this.btnBar = [];
      this.setBtnStatus();
    }
  }

  ngOnDestroy() {
    this.gridConfigService.resetRouterData();
    this.event.unsubscribe(this.formId);
  }
}
